#include "smartgaragedoor.h"
#include "globalvars.h"

#include "ohos_init.h"
#include "cmsis_os2.h"

int g_garagedoor_status = 0;
// int g_garagedoor_flag = 0;
// int g_garagedoor_control_flag = 0;

void Smartgaragedoor_task(void)
{
    Garagedoor_init(); //初始化门模块  
    printf("The garagedoor is activated successfully!!\r\n");
    usleep(100 * 1000);  //延时100ms
    while(1)
    {
        if(g_garagedoor_status == 0 && g_garagedoor_flag == 1)
        { 
            Garagedoor_switch(1);
            // usleep(3 * 1000 * 1000);
            usleep(600 * 1000);
            d:
            Garagedoor_switch(0);
            g_garagedoor_flag = 0;
            g_garagedoor_status = 1;
        }
            if(g_garagedoor_status == 1 && g_garagedoor_flag == 0 && g_garagedoor_control_flag == 0)
            {
                usleep(10 * 1000 * 1000);
                if(g_garagedoor_flag == 1)
                {
                    goto d;
                }
                Garagedoor_switch(2); // 关门
                // usleep(3 * 1000 *1000);
                usleep(700 * 1000);
                Garagedoor_switch(0); // 停机
                g_garagedoor_status = 0;   
            }

            if(g_garagedoor_control_flag == 1 && g_garagedoor_status == 0)
            {
                Garagedoor_switch(1);
                // usleep(3 * 1000 * 1000);
                usleep(600 * 1000);
                Garagedoor_switch(0);
                g_garagedoor_status = 1;
            }
            if(g_garagedoor_control_flag == 2 && g_garagedoor_status == 1)
            {
                Garagedoor_switch(2);
                // usleep(3 * 1000 * 1000);
                usleep(700 * 1000);
                Garagedoor_switch(0);
                g_garagedoor_control_flag = 0;
                g_garagedoor_status = 0;
            }
        usleep(3 * 1000 * 1000);
    }
}

void Smartgaragedoor_entry(void)
{
	usleep(3 * 1000 * 1000); //延时3s
	osThreadAttr_t attr; //任务属性结构体
	attr.name = "Smartgaragedoor_task"; //任务名称
	attr.stack_size = 1024; //任务内存大小
	attr.priority = 25;
    if(osThreadNew((osThreadFunc_t)Smartgaragedoor_task, NULL, &attr) == NULL)
    {
        printf("[Smartgaragedoor] Falied to create Smartgaragedoor_task!\n");
    }
    printf("[Smartgaragedoor] Succeed to create Smartgaragedoor_task!\n");
}

SYS_RUN(Smartgaragedoor_entry);